//
//  SecurityViewController.m
//  LocomotiveGuards
//
//  Created by XYS on 15/11/10.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

/**
 *
    http://docs.jpush.io/
    账号：it@jszhouhang.com   jszh007
 *
 */

#import "SecurityViewController.h"
#import "Masonry.h"
#import "SecurityHearder.h"
#import "SecurityMessageViewController.h"
#import "SecurityMessageFmdbModel.h"
#import "LoginViewController.h"
#import "AlertView.h"

#define SECURITYVIEWBACKGROUNDCOLOR [UIColor colorWithRed:23/255.0 green:127/255.0 blue:245/255.0 alpha:1]
#define ALARMVIEWSTATE_WIDTH         (SCREEN_HEIGHT /9 * 4)           //安全防护状态显示盘宽
#define ALARMVIEWSTATE_HEIGHT        (SCREEN_HEIGHT /9 * 4)           //安全防护状态显示盘高
#define ALARMVIEWSTATE_INTERNALAREA  (ALARMVIEWSTATE_WIDTH * 0.28)    //四种状态区域半径大小
#define ALARMVIEWSTATE_INTERNAL_SHIELD_AREA  (ALARMVIEWSTATE_INTERNALAREA * 0.31)    //盾牌半径大小

#define SECURITYSTATUSIMAGEVIEW_WIDTH  (ALARMVIEWSTATE_INTERNALAREA * 1.28) //状态图标大小
#define SECURITYSTATUSIMAGEVIEW_TIMEINTEVAL              5           //状态蓝色图标显示时间,单位:秒
#define SECURITYSTAUTSIMAGEVIEW_REFRESH_TIMEINTEVAL      1           //安全状态视图刷新时间间隔,单位:分钟

@interface SecurityViewController ()
{
    NSTimer * securityStatusTimer;       //安全状态视图刷新定时器
    
    NSTimer * securityAbnormalStatusTimer;
    NSTimer * securityLowPowerStatusTimer;
    NSTimer * securityCutStatusTimer;
    NSTimer * securityElecFenceStatusTimer;
    NSString * messageButtonImageName;
    NSString * msgText;
}

@property (nonatomic,strong) UIImageView * AlarmStateView;       //安全状态视图
@property (nonatomic,strong) UIButton    * AlarmSwitchButton;    //启用/解除安全保护
@property (nonatomic,strong) UIImageView * threePointView;       //三点
@property (nonatomic,strong) UIButton    * messageButton;        //消息按钮
@property (nonatomic,strong) UITextView  * messageTextView;      //消息内容
@property (nonatomic,strong) SecurityStatusObject * securityObject;
@property (nonatomic,assign) AlarmState currentAlarmState;      //当前一键防护状态为开启/关闭/正在查询

@property (nonatomic,strong) UIImageView * securityAbnormalStatusImageView;
@property (nonatomic,strong) UIImageView * securityLowPowerStatusImageView;
@property (nonatomic,strong) UIImageView * securityCutStatusImageView;
@property (nonatomic,strong) UIImageView * securityElecFenceStatusImageView;
@property (nonatomic, strong) NSString *userOrTourist;

@end

@implementation SecurityViewController

-(instancetype)init
{
    if (self = [super init])
    {
        [self addObserver:self forKeyPath:@"currentAlarmState" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld  context:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(remoteAPNNotificationHandle:) name:@"remoteAPNNotification" object:nil];
        messageButtonImageName = @"security_1pic_icon01";
        msgText = @"暂无消息";
        self.messageButton        = [[UIButton alloc]init];
        self.messageTextView      = [[UITextView alloc]init];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = SECURITYVIEWBACKGROUNDCOLOR;
    self.userOrTourist = [[NSUserDefaults standardUserDefaults] objectForKey:@"userOrTourist"];
    self.AlarmStateView       = [[UIImageView alloc]init];
    self.AlarmSwitchButton    = [[UIButton alloc]init];
    self.threePointView       = [[UIImageView alloc]init];
    
    [self.AlarmSwitchButton addTarget:self action:@selector(AlarmSwitchButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.AlarmSwitchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.AlarmSwitchButton.titleLabel.font = [UIFont systemFontOfSize:20];
    
    [self.messageButton setBackgroundImage:[UIImage imageNamed:messageButtonImageName] forState:UIControlStateNormal];
    [self.messageButton addTarget:self action:@selector(messageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.messageTextView.editable        = NO;
    self.messageTextView.selectable      = NO;
    self.messageTextView.backgroundColor = SECURITYVIEWBACKGROUNDCOLOR;
    self.messageTextView.textColor       = [UIColor whiteColor];
    self.messageTextView.font            = [UIFont systemFontOfSize:12];
    
    [self.view addSubview:self.AlarmStateView];
    [self.view addSubview:self.AlarmSwitchButton];
    [self.view addSubview:self.threePointView];
    [self.view addSubview:self.messageButton];
    [self.view addSubview:self.messageTextView];
    
    /*
        设置界面默认状态
     */
    [self setAlarmConfigView:AlarmStateOff];
    self.messageTextView.text = msgText;
    
    _currentAlarmState = AlarmStateNull;
    
    if ([self.userOrTourist isEqualToString:@"1"]) {
        self.securityObject = [[SecurityStatusObject alloc]init];
        self.securityObject.delegate = self;
    }

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changetabbarone" object:nil userInfo:@{@"key":@"1"}];
    
    [self.AlarmStateView remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(self.view.top).with.offset(SCREEN_HEIGHT*0.084);
        make.width.equalTo(ALARMVIEWSTATE_WIDTH);
        make.height.equalTo(ALARMVIEWSTATE_HEIGHT);
        
       
    }];
    
    [self.threePointView remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(self.AlarmStateView.bottom).with.offset(SCREEN_HEIGHT*0.05);
        make.width.equalTo(W*2);
        make.height.equalTo(SCREEN_HEIGHT*0.067);
    }];
    
    [self.AlarmSwitchButton remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(self.threePointView.bottom).with.offset(SCREEN_HEIGHT/20);
        make.width.equalTo(SCREEN_WIDTH*0.35);
        make.height.equalTo(SCREEN_HEIGHT*0.061);
    }];
    
    [self.messageButton remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.AlarmSwitchButton.bottom).with.offset(SCREEN_HEIGHT*0.05);
        make.width.equalTo(SCREEN_WIDTH*0.08);
        make.height.equalTo(SCREEN_HEIGHT*0.028);
        //make.left.equalTo(self.view.left).with.offset(SCREEN_WIDTH*0.09);
        make.left.equalTo(SCREEN_WIDTH*0.09);
    }];
    
    [self.messageTextView remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.messageButton.top).with.offset(-SCREEN_HEIGHT * 0.015);
        make.left.equalTo(self.messageButton.right).with.offset(SCREEN_WIDTH * 0.04);
        make.right.equalTo(self.view.right).with.offset(-SCREEN_WIDTH * 0.09);
        make.bottom.equalTo(self.view.bottom).with.offset(-SCREEN_HEIGHT * 0.02);

    }];
    
    if (securityStatusTimer)
    {
        [securityStatusTimer setFireDate:[NSDate distantPast]];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@",change);
    if ([keyPath isEqual:@"currentAlarmState"])
    {
        NSNumber * stateNumber = [change objectForKey:@"new"];
        if (stateNumber && 0 == stateNumber.intValue )
        {
            //开定时器
            if (!securityStatusTimer)
            {
                securityStatusTimer = [NSTimer scheduledTimerWithTimeInterval:SECURITYSTAUTSIMAGEVIEW_REFRESH_TIMEINTEVAL*60 target:self selector:@selector(securityStatusTimerHandler:) userInfo:nil repeats:YES];
            }
        }
        else
        {
            if (securityStatusTimer)
            {
                [securityStatusTimer invalidate];
                securityStatusTimer = nil;
            }
        }
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSLog(@"viewWillDisappear");
    if (securityStatusTimer)
    {
        [securityStatusTimer setFireDate:[NSDate distantFuture]];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.AlarmStateView = nil;
    self.AlarmSwitchButton = nil;    //启用/解除安全保护
    self.threePointView = nil;
    self.messageButton = nil;
    self.messageTextView = nil;
    self.securityObject = nil;
        
    self.securityAbnormalStatusImageView = nil;
    self.securityLowPowerStatusImageView = nil;
    self.securityCutStatusImageView = nil;
    self.securityElecFenceStatusImageView = nil;
}

- (void)dealloc
{
    self.securityObject.delegate = nil;//防止循环引用
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self removeObserver:self forKeyPath:@"currentAlarmState"];
    if (securityStatusTimer)
    {
        [securityStatusTimer invalidate];
        securityStatusTimer = nil;
    }
    
    [self removeAllSecurityStatusViewFromCurrentView];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint centerPosition;
    CGPoint currentPostion;
    
    UITouch * touch = [touches anyObject];
    currentPostion = [touch locationInView:self.view];
    NSLog(@"%f,%f",currentPostion.x,currentPostion.y);
    centerPosition = self.AlarmStateView.center;
    NSLog(@"%f,%f",centerPosition.x,centerPosition.y);
    /*
        判断点击的位置
     */
    double length = 0;
    
    /*
        判断点击位置是否在区域范围内
     */
    length = sqrt((currentPostion.x-centerPosition.x)*(currentPostion.x-centerPosition.x)+(currentPostion.y-centerPosition.y)*(currentPostion.y-centerPosition.y));
    NSLog(@"%f,%f",ALARMVIEWSTATE_INTERNAL_SHIELD_AREA,ALARMVIEWSTATE_INTERNALAREA);
    if (length < ALARMVIEWSTATE_INTERNAL_SHIELD_AREA || length > ALARMVIEWSTATE_INTERNALAREA)
    {
        return;
    }
    
    if ([self.userOrTourist isEqualToString:@"1"]) {
        /*
         异常状态
         */
        if (currentPostion.x < centerPosition.x && currentPostion.y < centerPosition.y)
        {
            [self.securityObject getSecurityAbnormalStatus];
        }
        
        /*
         低电报警状态
         */
        if (currentPostion.x > centerPosition.x && currentPostion.y < centerPosition.y)
        {
            [self.securityObject getSecurityLowPowerStatus];
        }
        
        /*
         剪断状态
         */
        if (currentPostion.x > centerPosition.x && currentPostion.y > centerPosition.y)
        {
            [self.securityObject getSecurityCutStatus];
        }
        
        /*
         电子围栏状态
         */
        if (currentPostion.x < centerPosition.x && currentPostion.y > centerPosition.y)
        {
            [self.securityObject getSecurityElecFenceStatus];
        }

    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
}


#pragma mark - APN Notification handler -

//bid = 78;
//loginId = 13188888888;
//msg = "007\U5b89\U5168\U536b\U58ebjson\U683c\U5f0f\U6d881\U606f\U6d4b71232";
//msgId = 601;
//time = 1450174442782;
//type = 1;


-(void)remoteAPNNotificationHandle:(NSNotification *) _notification
{
    [self.navigationController popToRootViewControllerAnimated:NO];
    messageButtonImageName = @"security_1pic_icon01_on";
    msgText = _notification.userInfo[@"msg"];
    if (self.messageButton)
    {
        [self.messageButton setBackgroundImage:[UIImage imageNamed:messageButtonImageName] forState:UIControlStateNormal];
    }
    if (self.messageTextView)
    {
        self.messageTextView.text = msgText;
    }
    
    SecurityMessageFmdbModel * message = [[SecurityMessageFmdbModel alloc]init];
    [message insertMessages:@[_notification.userInfo]];
}

#pragma mark - button clicked handle -

/**
 *  一键防护/解除防护 按钮点击
 *
 *  @param _btn
 */
- (void) AlarmSwitchButtonClicked:(UIButton *) _btn
{
    if ([self.userOrTourist isEqualToString:@"1"]) {
        AlarmState switchedToState;
    
        if ( _btn.tag == AlarmStateOn )
        {
            switchedToState = AlarmStateOff;
        }
        else if( _btn.tag == AlarmStateOff )
        {
            switchedToState = AlarmStateOn;
        }
        else
        {
            return;
        }
        [self.securityObject setAlarmConfig:switchedToState];
    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
}

/**
 *  消息按钮处理函数(信封图片)
 *
 *  @param _messageButton
 */
-(void) messageButtonClicked:(UIButton *) _messageButton
{
    NSLog(@"messageButtonClicked");
    messageButtonImageName = @"security_1pic_icon01";
    msgText = @"暂无消息";
    
    if (self.messageButton)
    {
        [self.messageButton setBackgroundImage:[UIImage imageNamed:messageButtonImageName] forState:UIControlStateNormal];
    }
    if (self.messageTextView)
    {
        self.messageTextView.text = msgText;
    }

    SecurityMessageViewController * securityMessageViewController = [[SecurityMessageViewController alloc]init];
    securityMessageViewController.userOrTourist = self.userOrTourist;
        [self.navigationController pushViewController:securityMessageViewController animated:NO];


}


#pragma mark - Timer handler -

/**
 *  安全状态定时刷新
 *
 *  @param _timer <#_timer description#>
 */
- (void) securityStatusTimerHandler:(NSTimer *) _timer
{
    
    if ([self.userOrTourist isEqualToString:@"1"]) {
        [self.securityObject getAlarmStatus];
        
        /**
         *  <#Description#>
         *
         *  获取安全状态信息，并本地保存getAlarmMsg
         */
        [self getAlarmMsgs];
    }
}

/**
 *  5分钟后删除手动查询状态显示的蓝色图标视图
 */
- (void) securityAbnormalStatusTimerHandler
{
    [securityAbnormalStatusTimer invalidate];
    securityAbnormalStatusTimer = nil;
    
    if (self.securityAbnormalStatusImageView)
    {
        if ( SecurityAbnormalStatusNormal == self.securityAbnormalStatusImageView.tag )
        {
            [self.securityAbnormalStatusImageView removeFromSuperview];
            self.securityAbnormalStatusImageView = nil;
        }
    }
}


- (void) securityLowPowerStatusTimerHandler
{
    [securityLowPowerStatusTimer invalidate];
    securityLowPowerStatusTimer = nil;
    
    if (self.securityLowPowerStatusImageView)
    {
        if ( SecurityLowPowerStatusNormal == self.securityLowPowerStatusImageView.tag )
        {
            [self.securityLowPowerStatusImageView removeFromSuperview];
            self.securityLowPowerStatusImageView = nil;
        }
    }
}

- (void) securityCutStatusTimerHandler
{
    [securityCutStatusTimer invalidate];
    securityCutStatusTimer = nil;
    
    if (self.securityCutStatusImageView)
    {
        if ( SecurityCutStatusNormal == self.securityCutStatusImageView.tag )
        {
            [self.securityCutStatusImageView removeFromSuperview];
            self.securityCutStatusImageView = nil;
        }
    }
}

- (void) securityElecFenceStatusTimerHandler
{
    [securityElecFenceStatusTimer invalidate];
    securityElecFenceStatusTimer = nil;
    
    if (self.securityElecFenceStatusImageView)
    {
        if ( SecurityElecFenceStatusNormal == self.securityElecFenceStatusImageView.tag )
        {
            [self.securityElecFenceStatusImageView removeFromSuperview];
            self.securityElecFenceStatusImageView = nil;
        }
    }
}


#pragma mark - Customed method -

/**
 *  删除所有的安全状态视图
 */
- (void) removeAllSecurityStatusViewFromCurrentView
{
    if (self.securityAbnormalStatusImageView)
    {
        [self.securityAbnormalStatusImageView removeFromSuperview];
        self.securityAbnormalStatusImageView = nil;
    }
    
    if (self.securityCutStatusImageView)
    {
        [self.securityCutStatusImageView removeFromSuperview];
        self.securityCutStatusImageView = nil;
    }
    
    if (self.securityLowPowerStatusImageView)
    {
        [self.securityLowPowerStatusImageView removeFromSuperview];
        self.securityLowPowerStatusImageView = nil;
    }
    
    if (self.securityElecFenceStatusImageView)
    {
        [self.securityElecFenceStatusImageView removeFromSuperview];
        self.securityElecFenceStatusImageView = nil;
    }
    
    [securityAbnormalStatusTimer invalidate];
    [securityLowPowerStatusTimer invalidate];
    [securityCutStatusTimer invalidate];
    [securityElecFenceStatusTimer invalidate];
    securityLowPowerStatusTimer = nil;
    securityCutStatusTimer = nil;
    securityElecFenceStatusTimer = nil;
    securityAbnormalStatusTimer = nil;
}

/**
 *  根据告警设置配置视图
 *
 *  @param _state 告警开启/关闭
 */
- (void) setAlarmConfigView:( AlarmState ) _state
{
    if ( _state == AlarmStateOn )
    {
        self.AlarmStateView.image = [UIImage imageNamed:@"security_1pic_photo01"];
        self.threePointView.image    = [UIImage imageNamed:@"security_1pic_photo02"];
        
        [self.AlarmSwitchButton setBackgroundImage:[UIImage imageNamed:@"security_1pic_btn01_on"] forState:UIControlStateNormal];
        [self.AlarmSwitchButton setBackgroundImage:[UIImage imageNamed:@"security_1pic_btn01_on"] forState:UIControlStateHighlighted];
        [self.AlarmSwitchButton setTitle:@"解除防护" forState:UIControlStateNormal];
        self.AlarmSwitchButton.tag = AlarmStateOn;
        self.currentAlarmState = AlarmStateOn;
        if ([self.userOrTourist isEqualToString:@"1"]) {
            [self.securityObject getAlarmStatus];
            [self getAlarmMsgs];
        }
        
    }
    else if( _state == AlarmStateOff )
    {
        self.AlarmStateView.image  = [UIImage imageNamed:@"security_2pic_photo01"];
        self.threePointView.image  = [UIImage imageNamed:@"security_2pic_photo02"];
        
        [self.AlarmSwitchButton setBackgroundImage:[UIImage imageNamed:@"security_2pic_btn01"] forState:UIControlStateNormal];
        [self.AlarmSwitchButton setBackgroundImage:[UIImage imageNamed:@"security_2pic_btn01"] forState:UIControlStateHighlighted];
        [self.AlarmSwitchButton setTitle:@"一键防护" forState:UIControlStateNormal];
        self.AlarmSwitchButton.tag = AlarmStateOff;
        self.currentAlarmState = AlarmStateOff;
        
        /*
            清除防护状态视图
         */
        [self removeAllSecurityStatusViewFromCurrentView];
    }
    else
    {
    
    }
}

/**
 *  设置状态视图:
 *
 *  @param _state 
                SecurityStateYellow:服务器定时刷新状态
                SecurityStateBlue:手动点击查询状态
 
           _SecurityAbnormalStatus:要设置的状态
    注：手动点击查询状态时，橘黄色图标显示，蓝色图标显示5秒后消失。服务器定时刷新状态时只显示橘黄色故障图标。通过self.securityAbnormalStatusImageView.tag判断上一状态。
 */
- (void) setSecurityAbnormalStatusView:( SecurityState ) _state
                SecurityAbnormalStatus:(SecurityAbnormalStatus) _SecurityAbnormalStatus
{
    if (_state == SecurityStateYellow)
    {
        /*
            服务器查询状态时，无需设置正常状态，只显示故障状态视图
         */
        if ( SecurityAbnormalStatusNormal == _SecurityAbnormalStatus )
        {
            if (self.securityAbnormalStatusImageView)
            {
                /*
                   上一状态为非正常状态时,清除状态(不显示)
                 */
                if (SecurityAbnormalStatusNormal != self.securityAbnormalStatusImageView.tag)
                {
                    [self.securityAbnormalStatusImageView removeFromSuperview];
                    self.securityAbnormalStatusImageView = nil;
                }
            }
            return;
        }
    }
    
    if (!self.securityAbnormalStatusImageView)
    {
        self.securityAbnormalStatusImageView = [[UIImageView alloc]init];
        [self.AlarmStateView addSubview:self.securityAbnormalStatusImageView];
        [self.securityAbnormalStatusImageView remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.AlarmStateView.centerX).with.offset(-ALARMVIEWSTATE_INTERNALAREA);
            make.centerY.equalTo(self.AlarmStateView.centerY).with.offset(-ALARMVIEWSTATE_INTERNALAREA);
            make.width.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
            make.height.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
        }];
    }
    
    self.securityAbnormalStatusImageView.tag = _SecurityAbnormalStatus;
    switch (_SecurityAbnormalStatus)
    {
            //正常
        case SecurityAbnormalStatusNormal:
            self.securityAbnormalStatusImageView.image = [UIImage imageNamed:@"other_prompt05"];
            securityAbnormalStatusTimer = [NSTimer scheduledTimerWithTimeInterval:SECURITYSTATUSIMAGEVIEW_TIMEINTEVAL target:self selector:@selector(securityAbnormalStatusTimerHandler) userInfo:nil repeats:NO];
            break;
            
            //非法位移
        case SecurityAbnormalStatusIllegalDisplacement:
            self.securityAbnormalStatusImageView.image = [UIImage imageNamed:@"other_prompt08"];
            break;
            
            //振动
        case SecurityAbnormalStatusVibration:
            self.securityAbnormalStatusImageView.image = [UIImage imageNamed:@"other_prompt09"];
            break;
            
            //锁定
        case SecurityAbnormalStatusLock:
            self.securityAbnormalStatusImageView.image = [UIImage imageNamed:@"other_prompt10"];
            break;
            
        default:
            break;
    }
}


/**
 *  设置状态视图:
 *
 *  @param _state
                SecurityStateYellow:服务器定时刷新状态
                SecurityStateBlue:手动点击查询状态
 
           _SecurityLowPowerStatus:要设置的状态
    注：手动点击查询状态时，橘黄色图标显示，蓝色图标显示5分钟后消失。服务器定时刷新状态时只显示橘黄色故障图标。通过self.securityLowPowerStatusImageView.tag判断上一状态。
 */
- (void) setSecurityLowPowerStatusView:( SecurityState ) _state
                SecurityLowPowerStatus:(SecurityLowPowerStatus) _SecurityLowPowerStatus
{
    if (_state == SecurityStateYellow)
    {
        /*
            服务器查询状态时，无需设置正常状态，只显示故障状态视图
         */
        if ( SecurityLowPowerStatusNormal == _SecurityLowPowerStatus )
        {
            if (self.securityLowPowerStatusImageView)
            {
                /*
                    上一状态为非正常状态时,清除状态(不显示)
                 */
                if (SecurityAbnormalStatusNormal != self.securityLowPowerStatusImageView.tag)
                {
                    [self.securityLowPowerStatusImageView removeFromSuperview];
                    self.securityLowPowerStatusImageView = nil;
                }
            }
            return;
        }
    }
    
    if (!self.securityLowPowerStatusImageView)
    {
        self.securityLowPowerStatusImageView = [[UIImageView alloc]init];
        [self.AlarmStateView addSubview:self.securityLowPowerStatusImageView];
        [self.securityLowPowerStatusImageView remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.AlarmStateView.centerX).with.offset(ALARMVIEWSTATE_INTERNALAREA);
            make.centerY.equalTo(self.AlarmStateView.centerY).with.offset(-ALARMVIEWSTATE_INTERNALAREA);
            make.width.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
            make.height.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
        }];
    }
    
    self.securityLowPowerStatusImageView.tag = _SecurityLowPowerStatus;
    switch (_SecurityLowPowerStatus)
    {
            //正常
        case SecurityLowPowerStatusNormal:
            self.securityLowPowerStatusImageView.image = [UIImage imageNamed:@"other_prompt01"];
            securityLowPowerStatusTimer = [NSTimer scheduledTimerWithTimeInterval:SECURITYSTATUSIMAGEVIEW_TIMEINTEVAL target:self selector:@selector(securityLowPowerStatusTimerHandler) userInfo:nil repeats:NO];
            break;
            
            //低电量
        case SecurityLowPowerStatusLowPower:
            self.securityLowPowerStatusImageView.image = [UIImage imageNamed:@"other_prompt07"];
            break;
            
            //断电
        case SecurityLowPowerStatusinterrupt:
            self.securityLowPowerStatusImageView.image = [UIImage imageNamed:@"security_3pic_prompt"];
            break;
            
        default:
            break;
    }
}


/**
 *  设置状态视图:
 *
 *  @param _state
                SecurityStateYellow:服务器定时刷新状态
                SecurityStateBlue:手动点击查询状态
 
           _SecurityCutStatus:要设置的状态
    注：手动点击查询状态时，橘黄色图标显示，蓝色图标显示5分钟后消失。服务器定时刷新状态时只显示橘黄色故障图标。通过self.securityLowPowerStatusImageView.tag判断上一状态。
 */
- (void) setSecurityCutStatusView:( SecurityState ) _state
                SecurityCutStatus:(SecurityCutStatus) _SecurityCutStatus
{
    if (_state == SecurityStateYellow)
    {
        /*
         服务器查询状态时，无需设置正常状态，只显示故障状态视图
         */
        if ( SecurityCutStatusNormal == _SecurityCutStatus )
        {
            if (self.securityCutStatusImageView)
            {
                /*
                 上一状态为非正常状态时,清除状态(不显示)
                 */
                if (SecurityCutStatusNormal != self.securityCutStatusImageView.tag)
                {
                    [self.securityCutStatusImageView removeFromSuperview];
                    self.securityCutStatusImageView = nil;
                }
            }
            return;
        }
    }
    
    if (!self.securityCutStatusImageView)
    {
        self.securityCutStatusImageView = [[UIImageView alloc]init];
        [self.AlarmStateView addSubview:self.securityCutStatusImageView];
        [self.securityCutStatusImageView remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.AlarmStateView.centerX).with.offset(ALARMVIEWSTATE_INTERNALAREA);
            make.centerY.equalTo(self.AlarmStateView.centerY).with.offset(ALARMVIEWSTATE_INTERNALAREA);
            make.width.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
            make.height.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
        }];
    }
    
    self.securityCutStatusImageView.tag = _SecurityCutStatus;
    switch (_SecurityCutStatus)
    {
            //正常
        case SecurityCutStatusNormal:
            self.securityCutStatusImageView.image = [UIImage imageNamed:@"other_prompt03"];
            securityCutStatusTimer = [NSTimer scheduledTimerWithTimeInterval:SECURITYSTATUSIMAGEVIEW_TIMEINTEVAL target:self selector:@selector(securityCutStatusTimerHandler) userInfo:nil repeats:NO];
            break;
            
            //剪断
        case SecurityCutStatusCutted:
            self.securityCutStatusImageView.image = [UIImage imageNamed:@"security_4pic_prompt"];
            break;
            
        default:
            break;
    }
}


/**
 *  设置电子围栏状态视图:
 *
 *  @param _state
                SecurityStateYellow:服务器定时刷新状态
                SecurityStateBlue:手动点击查询状态
 
           _SecurityElecFenceStatus:要设置的状态
    注：手动点击查询状态时，橘黄色图标显示，蓝色图标显示5分钟后消失。服务器定时刷新状态时只显示橘黄色故障图标。通过self.securityElecFenceStatusImageView.tag判断上一状态。
 */
- (void) setSecurityElecFenceStatusView:( SecurityState ) _state
                SecurityElecFenceStatus:(SecurityElecFenceStatus) _SecurityElecFenceStatus
{
    if (_state == SecurityStateYellow)
    {
        /*
         服务器查询状态时，无需设置正常状态，只显示故障状态视图
         */
        if ( SecurityElecFenceStatusNormal == _SecurityElecFenceStatus )
        {
            if (self.securityElecFenceStatusImageView)
            {
                /*
                 上一状态为非正常状态时,清除状态(不显示)
                 */
                if (SecurityCutStatusNormal != self.securityElecFenceStatusImageView.tag)
                {
                    [self.securityElecFenceStatusImageView removeFromSuperview];
                    self.securityElecFenceStatusImageView = nil;
                }
            }
            return;
        }
    }
    
    if (!self.securityElecFenceStatusImageView)
    {
        self.securityElecFenceStatusImageView = [[UIImageView alloc]init];
        [self.AlarmStateView addSubview:self.securityElecFenceStatusImageView];
        [self.securityElecFenceStatusImageView remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.AlarmStateView.centerX).with.offset(-ALARMVIEWSTATE_INTERNALAREA);
            make.centerY.equalTo(self.AlarmStateView.centerY).with.offset(ALARMVIEWSTATE_INTERNALAREA);
            make.width.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
            make.height.equalTo(SECURITYSTATUSIMAGEVIEW_WIDTH);
        }];
    }
    
    self.securityElecFenceStatusImageView.tag = _SecurityElecFenceStatus;
    switch (_SecurityElecFenceStatus)
    {
            //正常
        case SecurityElecFenceStatusNormal:
            self.securityElecFenceStatusImageView.image = [UIImage imageNamed:@"other_prompt04"];
            securityElecFenceStatusTimer = [NSTimer scheduledTimerWithTimeInterval:SECURITYSTATUSIMAGEVIEW_TIMEINTEVAL target:self selector:@selector(securityElecFenceStatusTimerHandler) userInfo:nil repeats:NO];
            break;
            
            //越界
        case SecurityElecFenceStatusOutofBounds:
            self.securityElecFenceStatusImageView.image = [UIImage imageNamed:@"security_5pic_prompt"];
            break;
            
        default:
            break;
    }
}

/**
 *  清除安全状态视图
 */
- (void)clearSecurityStatusView
{
    [self removeAllSecurityStatusViewFromCurrentView];
}

/**
 *  主动获取用户车辆的告警信息
 */
- (void) getAlarmMsgs
{
    //http://appif.jszhtech.com:8080/ebappif/appif/getAlarmMsgs.do?loginId=18602556151
    
    /**
     *  消息编辑界面的数据只从本地获取
     */
    NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    NSString * urlMethod = [NSString stringWithFormat:@"%@getAlarmMsgs.do",urlstring];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:urlMethod withParam:@{@"loginId":loginId} success:
     ^(AFHTTPRequestOperation *operation, id responseObject) {
         NSDictionary * responseDict = responseObject;
         
         NSNumber * flag = [responseObject objectForKey:@"flag"];
         if (0 == flag.longValue )
         {
             NSArray * msgList = [responseObject objectForKey:@"list"];
             
             if ( msgList && msgList.count > 0 )
             {
                 SecurityMessageFmdbModel * messageModel = [[SecurityMessageFmdbModel alloc]init];
                 [messageModel insertMessages:msgList];
                 
                 /*
                    界面显示接收到的消息
                  */
                 if (messageModel.lastMessage)
                 {
                     messageButtonImageName = @"security_1pic_icon01_on";
                     [self.messageButton setBackgroundImage:[UIImage imageNamed:messageButtonImageName] forState:UIControlStateNormal];
                     self.messageTextView.text = messageModel.lastMessage[@"msg"];
                 }
             }
         }
         else
         {
             NSLog(@"%@",responseDict[@"msg"]);
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         messageButtonImageName = @"security_1pic_icon01";
         [self.messageButton setBackgroundImage:[UIImage imageNamed:messageButtonImageName] forState:UIControlStateNormal];
         self.messageTextView.text = @"暂无消息";
         NSLog(@"查询防护状态失败！");
     }];
}


@end
